<template>
  <div>
    <h2>植物养殖系统</h2>
    <p>温度: {{ temperature }}℃</p>
    <p>湿度: {{ humidity }}%</p>
    <div>
      <button @click="toggleDevice(1)">水泵 {{ pumpStatus ? '开' : '关' }}</button>
      <button @click="toggleDevice(2)">加湿器 {{ humidifierStatus ? '开' : '关' }}</button>
      <button @click="toggleDevice(3)">遮阳板 {{ sunshadeStatus ? '开' : '关' }}</button>
      <button @click="toggleDevice(4)">加热器 {{ heaterStatus ? '开' : '关' }}</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import mqtt from 'mqtt';

// MQTT 配置
const clientId = `mqtt_${Math.random().toString(16).slice(3)}`;
const host = 'ws://123.56.231.114:8083/mqtt';
const options = {
  clientId,
  clean: true,
  connectTimeout: 4000,
  username: 'admin',
  password: 'admin',
  reconnectPeriod: 1000,
};

// 状态变量
const temperature = ref(0);
const humidity = ref(0);
const pumpStatus = ref(false);
const humidifierStatus = ref(false);
const sunshadeStatus = ref(false);
const heaterStatus = ref(false);

// 创建 MQTT 客户端
const client = mqtt.connect(host, options);

// 连接成功处理
client.on('connect', () => {
  console.log('Connected to MQTT broker');
  // 订阅主题
  client.subscribe('zwxt/out', (err) => {
    if (!err) {
      console.log('Subscribed to topic: zwxt/out');
    }
  });
});

// 接收消息处理
client.on('message', (topic, message) => {
  if (topic === 'zwxt/out') {
    try {
      const data = JSON.parse(message.toString());
      if (data.mode === 1) {
        temperature.value = data.val;
      } else if (data.mode === 2) {
        humidity.value = data.val;
      }
    } catch (error) {
      console.error('Error parsing JSON:', error);
    }
  }
});

// 发送消息函数
const sendMessage = (mode, val) => {
  const payload = JSON.stringify({ mode, val });
  client.publish('zwxt/in', payload, (err) => {
    if (err) {
      console.error('Error publishing message:', err);
    } else {
      console.log('Message published:', payload);
    }
  });
};

// 切换设备状态函数
const toggleDevice = (mode) => {
  let status;
  switch (mode) {
    case 1:
      status = pumpStatus.value;
      pumpStatus.value = !status;
      break;
    case 2:
      status = humidifierStatus.value;
      humidifierStatus.value = !status;
      break;
    case 3:
      status = sunshadeStatus.value;
      sunshadeStatus.value = !status;
      break;
    case 4:
      status = heaterStatus.value;
      heaterStatus.value = !status;
      break;
    default:
      break;
  }
  const val = status ? 0 : 1;
  sendMessage(mode, val);
};

onMounted(() => {
  // 初始化连接
  client.connect();
});
</script>